import requests
from PyQt5.QtCore import QObject, pyqtSignal
import os
from dotenv import load_dotenv
from pathlib import Path

class AuthClient(QObject):
    login_success = pyqtSignal(dict)  # 登录成功信号
    login_failed = pyqtSignal(str)    # 登录失败信号
    
    def __init__(self, base_url="http://localhost:5000"):
        super().__init__()
        # 加载.env文件（从项目根目录）
        env_path = Path(__file__).parent.parent.parent / '.env'
        load_dotenv(env_path)
        
        # 获取配置（环境变量优先，不存在则使用默认值）
        self.base_url = os.getenv('API_BASE_URL', 'http://localhost:5000')
        self.token = None
    
    def login(self, username, password):
        try:
            response = requests.post(
                f"{self.base_url}/api/auth/login",
                json={"username": username, "password": password}
            )
            
            data = response.json()  # 获取响应数据
            print(data)
            if response.status_code == 200:
                if data.get('code') == 200:  # 检查状态
                    # self.token = data.get('data', {}).get('username')
                    self.login_success.emit(data)
                else:
                    # 处理业务逻辑错误
                    error = data.get('error', '登录失败，请检查用户名和密码')
                    self.login_failed.emit(error)
            else:
                # 处理HTTP错误
                error = data.get('error', f'登录失败，状态码: {response.status_code}')
                self.login_failed.emit(error)
                
        except requests.exceptions.RequestException as e:
            self.login_failed.emit(f"网络错误: {str(e)}")
        except ValueError:  # JSON解析错误
            self.login_failed.emit("服务器返回数据格式错误")